<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="getTitle"
    :close-func="closeFunc"
    @ok="handleSubmit"
    destroyOnClose
  >
    <BasicForm @register="registerForm">
      <template #permissionSlot="{ model, field }">
        <Input allow-clear v-model:value="model[field]" placeholder="请输入" />
        <section class="text-12px mt-4px color-[#00000073]"
          >接口中定义权限标识：@SaCheckPermission("")</section
        >
      </template>
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form/index';
  import { formSchema } from './data';
  import { Input } from 'ant-design-vue';
  import { addMenuApi, updateMenuApi, listMenuApi } from '@/api/system/menu';
  import type { SystemMenuItem } from '@/api/system/model/menuModel';

  const rowId = ref<string>();
  const menuList = ref([]);

  const emit = defineEmits(['success', 'register']);

  const [registerForm, { setFieldsValue, resetFields, validate }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  });

  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    resetFields();
    setModalProps({ confirmLoading: false });
    const { id } = data;
    const res = await listMenuApi();
    menuList.value = res;
    if (id) {
      rowId.value = id;
      setFieldsValue({ ...data });
    }
  });

  const getTitle = computed(() => (!unref(rowId) ? '新增菜单' : '编辑菜单'));

  const closeFunc = async () => {
    await resetFields();
    rowId.value = undefined;
    return true;
  };
  /** 根据parentId获取parentIds */
  function getParentIdsById(id) {
    const parentIds: string[] = [];
    const traverse = (data) => {
      if (data && data.length) {
        for (let item of data) {
          parentIds.push(item.id);
          if (item.id === id) {
            return;
          } else {
            if (item.children && item.children.length) traverse(item.children);
            traverse(item.children);
            parentIds.pop();
          }
        }
      } else {
        return;
      }
    };
    traverse(menuList.value);
    return parentIds;
  }

  async function handleSubmit() {
    try {
      const values: SystemMenuItem = await validate();
      setModalProps({ confirmLoading: true });
      let parentIds = await getParentIdsById(values.parentId).join(',');
      const parentId = values.parentId === '0' ? null : values.parentId;
      if (parentIds) {
        parentIds = '0,' + parentIds;
      }
      if (values.type === '1') {
        values.componentPath = 'Layout';
        values.menuCacheFlag = undefined;
      }
      if (values.type === '3') {
        values.menuExtFlag = undefined;
        values.menuCacheFlag = undefined;
      }
      // TODO custom api
      unref(rowId)
        ? await updateMenuApi({ ...values, id: rowId.value, parentIds, parentId })
        : await addMenuApi({ ...values, parentIds, parentId });
      closeModal();
      closeFunc();
      emit('success');
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }
</script>
